package common.action;

import common.domain.Product;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用来当作数据库使用
 */
@Service
public class SaveProductAction {

    private Map<Integer, Product> resultMap = new HashMap<Integer, Product>();
    private Integer productId = 1;

    public SaveProductAction() {
        Product product1 = new Product("MacBookPro", "电脑", 12888.88f);
        Product product2 = new Product("《Spring MVC 学习指南》", "书本", 39.98f);
        resultMap.put(productId++, product1);
        resultMap.put(productId++, product2);
    }

    public Integer save(Product product) {
        Integer id = productId++;
        resultMap.put(id, product);
        return id;
    }

    public Product delete(Integer productId) {
        return resultMap.remove(productId);
    }

    public List<Product> findAll() {
        List<Product> resultList = new ArrayList<Product>();
        for (Integer i = 0; i < productId; i++) {
            if (resultMap.get(i) != null) {
                resultList.add(resultMap.get(i));
            }
        }
        return resultList;
    }

    public Product findById(Integer id) {
        return resultMap.get(id);
    }


}
